<script setup lang="ts">
import { ref, Ref, unref, watchEffect } from "vue";
import { ElSelect, ElOption } from "element-plus";

import type { TOptions } from "../type";
import usePage from "@/hooks/usePage";
import { throttle } from "lodash-es";

const {
  options = [],
  valueKey = "value",
  labelKey = "label",
  searchKey,
  disabledKey = "disabled",
  fetchUrl = "",
  fetchOptions = {},
} = defineProps<{
  valueKey?: string;
  labelKey?: string;
  searchKey?: string;
  disabledKey?: string;
  options?: TOptions | Ref<TOptions>;

  render?: any;
  renderContent?: (e: any) => any;

  fetchUrl?: string | Ref<string>;
  fetchOptions?: any;
  optionPropRender?: (item: any) => TOptions;
}>();

const search = ref<Record<string, any>>(fetchOptions.defaultSearch || {});
const renderOptions = ref(options as any[]);
watchEffect(() => {
  renderOptions.value = options as any[];
});

const { list, execute, onFetchResponse } = usePage<any[]>(fetchUrl, {
  ...fetchOptions,
  defaultSearch: search,
  immediate: !!unref(fetchUrl),
});

onFetchResponse(() => {
  renderOptions.value = list.value;
});

const remoteMethod = throttle((val: string) => {
  if (searchKey) {
    search.value[searchKey] = val;
    execute();
  }
});
</script>

<template>
  <ElSelect :remote-method="remoteMethod">
    <ElOption
      v-for="item in renderOptions"
      :key="item[valueKey]"
      :value="item[valueKey]"
      :label="item[labelKey]"
      :disabled="item[disabledKey]"
    />
  </ElSelect>
</template>
